#endcoding:utf-8
module ApplicationHelper
  def logged_in?
    if session[:user_id].nil?
      redirect_to login_path
    end
  end

  def log_in user
    session[:user_id] = user.id
  end

  def current_user? cuid
    if session[:user_id].nil?
      return false
    end
    cuid.to_i==session[:user_id]
  end

  def userinfo
    if !session[:user_id].nil?
      User.find(session[:user_id])
    else
      nil
    end

  end

  def getcardinfo user
      if user.user_type
        FactoryInfo.find_by(:user_id=>user.id)
      else
        CounselorInfo.find_by(:user_id=>user.id)
      end
  end

  def iscounselor?(cuser)
    !cuser[:user_type]
  end

  def isfactory?(cuser)
    cuser[:user_type]
  end

  def counselorgo
    if iscounselor?(userinfo)
      flash[:danger] = "只有工厂用户才能发布验厂需求"
      redirect_to userinfo
    end
  end

  def factorygo
    if isfactory?
      flash[:info] = "只有咨询师用户才能找需求"
      redirect_to userinfo
    end
  end

  def getname userid
    user = User.find(userid)
    user[:name]
  end

  def logged?
    !session[:user_id].nil?
  end

  def hasOffered? demandid
    Offer.where("user_id="+session[:user_id].to_s+" AND demand_id="+demandid.to_s).any?
  end

  def unread_msg_count
    user = User.find(session[:user_id])
    user.messages.where("readed=0").count
  end

  def send_message(reciver,content,demand)
    @message = Message.new({:user_id=>reciver,:content=>content,:readed=>0,:demand_id=>demand})
    @message.save
  end
  def uid
    session[:user_id].to_s
  end
  def infoid
    info = isfactory?(userinfo) ? FactoryInfo.find_by(:user_id=>uid) : CounselorInfo.find_by(:user_id=>uid)
    info.id.to_s
  end
  def ismydemand? demand
    demand.user_id == uid.to_i
  end
  def isbited? offer,demand
    deal = Deal.where("offer_id="+offer.id.to_s+" AND demand_id="+demand.id.to_s)
    deal.any?
  end

  def message_link message,url
    '<span url="'+url+'" href="javascript:void">'+message+'</span>'
  end

  def ismyoffer?offer
    offer.user_id==uid.to_i
  end

  def latest_factory_activities cuser
    @acitvities = Demand.where("user_id IN (?)", cuser.following_ids).order('created_at desc').limit(6)
  end

  def alert(type,message)
    '<div class="alert alert-'+type+'" role="alert">'+message+'</div>'.html_safe if !message.nil?
  end

  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end
# 􀂿􀁉􀀰􀂑􀉉􀇥􀇞􀂄􀆔􀂥􀂦
  def store_location
    session[:forwarding_url] = request.url if request.get?
  end

  def avatar user,style
    if user.profile.nil?
      raw '<img src="/assets/avatar.png" class="'+style+'">'
    else
      raw '<img src="'+user.profile.avatar_url+'" class="'+style+'">'
    end
  end

  def hot_tags
    Tag.order('use_time desc').limit(20)
  end
end
